package com.czk.channel.channelPractice;

import org.junit.Test;

import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * nio文件拷贝的方式
 *
 * @Author:ChenZhangKun
 * @Date: 2021/5/31 14:06
 */
public class FileChannelTest {
    /**
     * 利用内存映射进行拷贝
     *
     * @throws IOException
     */
    @Test
    public void method_3() throws IOException {
        // 内存映射的方式
        FileChannel inChannel = FileChannel.open(Paths.get("D:\\简历\\2.txt"), StandardOpenOption.READ);
        FileChannel outChannel = FileChannel.open(Paths.get("D:\\简历\\kd.txt"),
                StandardOpenOption.WRITE,
                StandardOpenOption.READ,
                StandardOpenOption.CREATE);
        // 通过内存映射的方式拷贝
        MappedByteBuffer inMap = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size());
        MappedByteBuffer outMap = outChannel.map(FileChannel.MapMode.READ_WRITE, 0, inChannel.size());
        // 创建缓冲区
        // inMap.limit()为可读的资源
        byte[] b = new byte[inMap.limit()];
        // 将其放入字节中
        inMap.get(b);
        outMap.put(b);
        outChannel.close();
        inChannel.close();
    }

    /**
     * transferFrom的方式
     *
     * @throws IOException
     */
    @Test
    public void method_2() throws IOException {
        // 输入流
        FileChannel inChannel = FileChannel.open(Paths.get("D:\\简历\\2.txt"), StandardOpenOption.READ);
        // 输出流
        FileChannel outChannel = FileChannel.open(Paths.get("D:\\简历\\nzq.txt"), StandardOpenOption.WRITE
                , StandardOpenOption.READ
                , StandardOpenOption.CREATE);
        // 拷贝
        outChannel.transferFrom(inChannel, 0, inChannel.size());
        inChannel.close();
        outChannel.close();
    }

    /**
     * 通过transferTo方式
     */
    @Test
    public void method_1() throws IOException {
        // channel的输入流
        FileChannel inChannel = FileChannel.open(Paths.get("D:\\简历\\2.txt"), StandardOpenOption.READ);
        // channel的写出流
        FileChannel outChannel = FileChannel.open(Paths.get("D:\\简历\\czk.txt"), StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
        // 写入
        inChannel.transferTo(0, inChannel.size(), outChannel);
        inChannel.close();
        outChannel.close();
    }
}
